package com.example.compreshensiveshop.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.example.compreshensiveshop.dto.PayMessageDTO;
import com.example.compreshensiveshop.handler.PaySuccessHandler;
import com.example.compreshensiveshop.service.PayService;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/pay")
@Slf4j
public class PayController {
    @Autowired
    private PayService payService;
    @Value("${alipay.alipay_public_key}")
    private String alipayPublicKey;
    @Autowired
    private PaySuccessHandler paySuccessHandler;

      @PostMapping ("/pay")
     public String pay(@RequestBody PayMessageDTO payMessageDTO) throws AlipayApiException {
      return payService.pay( payMessageDTO.getProductName(), payMessageDTO.getOrderId(), payMessageDTO.getTotalAmount());
     }
    @RequestMapping(value = "/alipay_notify_url", method = RequestMethod.POST)
    public String payNotify(HttpServletRequest request) throws AlipayApiException {


        log.info("支付回调，消息接收 {}", request.getParameter("trade_status"));
        if (!request.getParameter("trade_status").equals("TRADE_SUCCESS")) {
            return "false";
        }
        Map<String, String> params = new HashMap<>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (String name : requestParams.keySet()) {
            params.put(name, request.getParameter(name));
        }
        String tradeNo = params.get("out_trade_no");
        String gmtPayment = params.get("gmt_payment");
        String alipayTradeNo = params.get("trade_no");

        String sign = params.get("sign");
        String content = AlipaySignature.getSignCheckContentV1(params);
        boolean checkSignature = AlipaySignature.rsa256CheckContent(content, sign, alipayPublicKey, "UTF-8"); // 验证签名
        // 支付宝验签
        if (!checkSignature) {
            return "false";
        }
        Map<String, String> paymentData = new HashMap<>();
        // 验签通过
        log.info("支付回调，交易名称: {}", params.get("subject"));
        log.info("支付回调，交易状态: {}", params.get("trade_status"));
        log.info("支付回调，支付宝交易凭证号: {}", params.get("trade_no"));
        log.info("支付回调，商户订单号: {}", params.get("out_trade_no"));
        log.info("支付回调，交易金额: {}", params.get("total_amount"));
        log.info("支付回调，买家在支付宝唯一id: {}", params.get("buyer_id"));
        log.info("支付回调，买家付款时间: {}", params.get("gmt_payment"));
        log.info("支付回调，买家付款金额: {}", params.get("buyer_pay_amount"));
        log.info("支付回调，支付回调，更新订单 {}", tradeNo);
        paymentData.put("orderId", tradeNo);
        paymentData.put("tradeNo", alipayTradeNo);
        paymentData.put("tradeStatus", "TRADE_SUCCESS");
        paymentData.put("totalAmount", params.get("total_amount"));
        paymentData.put("gmtPayment", params.get("gmt_payment"));
        paymentData.put("buyerId", params.get("buyer_id"));
        //todo 这里需要改变订单的状态，支付成功了撒,使用handler类
        paySuccessHandler.handleSuccess(Long.parseLong(tradeNo),1);
        return "success";
    }
    /**
     * 支付成功后的回调
     * @param orderId
     * @param totalAmount
     * @param response
     * @return
     */
    @RequestMapping(value = "/payment/result", method = RequestMethod.GET)
    public void payReturn(
            @RequestParam("out_trade_no") String orderId,
            @RequestParam("total_amount") String totalAmount,
            HttpServletResponse response) throws IOException {

        log.info("支付return_url回调，订单号: {}", orderId);
        log.info("支付return_url回调，订单金额: {}", totalAmount);

        // 重定向到前端Vue页面，同时传递金额参数
        String frontendUrl = "http://115.190.105.127:8081/payment/result?orderId=" + orderId + "&totalAmount=" + totalAmount;
        response.sendRedirect(frontendUrl);
    }
}
